package com.example.cachedemo;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

public class AppUtil {
    // 本工具类的tag
    private static final String TAG = "AppUtil";

    /**
     *
     * @param context 上下文
     * @return 版本号version Code
     */
    public static int getAppVersion(Context context) {
        // 默认填1
        int appVersion = 1;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                appVersion = (int)packageInfo.getLongVersionCode();
            } else {
                appVersion = packageInfo.versionCode;
            }
            Log.d(TAG, "appVersionCode:" + appVersion);
        } catch (PackageManager.NameNotFoundException e){
            e.printStackTrace();
        }

        return appVersion;
    }
}
